#include "../include/head.h"
#include "../include/func.h"

int send_file_sendfile(int fd_socket, char *filename, int filesize)
{
    //打开传输文件
    int fd_file = open(filename, O_RDONLY);
    ERROR_CHECK(fd_file, -1, "open");

    //发文件内容
    sendfile(fd_socket, fd_file, 0, filesize);

    //关闭传输文件
    close(fd_file);
    return 0;
}

int send_file_train(int fd_socket, char *filename)
{
    //打开传输文件
    int fd_file = open(filename, O_RDONLY);
    ERROR_CHECK(fd_file, -1, "open");
    Train_t train;	 //定义一个小火车，用来传输文件
    int ret = -1;

    //断点续传
    //从客户端接收文件大小，如果大于0就偏移文件指针
    off_t offset = 0;
    recv(fd_socket, &offset, sizeof(off_t), MSG_WAITALL);
    if (offset) {
        lseek(fd_file, offset, SEEK_SET);
    }

    //再发文件内容
    while (1) {
        memset(&train, 0, sizeof(Train_t));
        train._data_len = read(fd_file, train._data, sizeof(train._data));
        printf("data_len:%d\n", train._data_len);
        if (0 == train._data_len) {
            //传输完成，通知客户端，然后退出循环
            ret = send(fd_socket, &train._data_len, 4, 0);
            ERROR_CHECK(ret, -1, "send");
            //关闭传输文件
    		close(fd_file);
            return 0;
        }

        ret = send(fd_socket, &train, sizeof(int) + train._data_len, 0);
        if (-1 == ret) {
            //客户端异常断开，退出循环
            printf("client erupt!\n");
            //关闭传输文件
    		close(fd_file);
            return -2;
        }
    }
}
